package com.example.teamtribe;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.BitmapFactory;
import android.os.IBinder;

import com.example.teamtribe.utils.ImageUtil;

import org.litepal.LitePal;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class Application extends android.app.Application {

    private static Context context;
    private static UpdateService.Binder binder;
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder = (UpdateService.Binder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        LitePal.initialize(this);
        bindService(new Intent(Application.this, UpdateService.class), conn, Service.BIND_AUTO_CREATE);

        transform(R.drawable.head_default, "00000000000000000000000000000000");
    }

    @Override
    public void onTerminate() {
        unbindService(conn);
        super.onTerminate();
    }

    public static Context getContext() {
        return context;
    }

    public static UpdateService.Binder getBinder() {
        return binder;
    }

    public static void transform(int id, String filename) {
        File file = new File(Application.getContext().getFilesDir() + File.separator + filename);
        if (!file.exists()) {
            FileOutputStream fos = null;
            try {
                fos = Application.getContext().openFileOutput(filename, Context.MODE_PRIVATE);
                fos.write(ImageUtil.toBytes(BitmapFactory.decodeResource(Application.getContext().getResources(), id)));
                fos.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
